from __future__ import print_function

from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras import utils

#设置训练参数
batch_size = 128  #批量大小
num_classes = 10  #类别数量=10
epochs = 1

#加载数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()

#数据预处理
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255 # 缩放，x-xmin/xmax-xmin, x_train = x_train / 255
X_test /= 255
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

#多分类需进行独热编码
y_train = utils.to_categorical(y_train, num_classes)
y_test = utils.to_categorical(y_test, num_classes)

#构建模型
model = Sequential()

model.add(Dense(256, input_dim=784,
                kernel_initializer='glorot_uniform', activation='relu')) #kernel_initializer参数初始化方法
model.add(Dropout(0.3)) # 失活比例0.3

model.add(Dense(256, kernel_initializer='glorot_uniform', activation='relu'))
model.add(Dropout(0.3))

model.add(Dense(256, kernel_initializer='glorot_uniform', activation='relu'))
model.add(Dropout(0.3))

model.add(Dense(256, kernel_initializer='glorot_uniform', activation='relu'))
model.add(Dropout(0.3))

model.add(Dense(num_classes, activation='softmax'))

#模型编译配置compile
model.compile(loss='categorical_crossentropy',
              optimizer='adam', metrics=['accuracy'])

#训练模型：batch_size批量大小，validation_split=0.2拿出训练集中20%的数据作为验证集
history = model.fit(X_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_split=0.2)

# ==============================================================================
# predict
#模型预测评估
score = model.evaluate(X_test, y_test, batch_size=batch_size)
print('\nTest loss:', score[0])  #损失
print('Test accuracy:', score[1]) #准确率
'''
Test loss: 0.0742975851574
Test accuracy: 0.9811
'''
